from math import fabs, log
from random import uniform
from time import time
from pygsl.ieee import set_mode, extended_precision
import Image, ImageDraw
from set_cover import approx


_MIN_ERROR = 10**-15
_IMAGE_SIZE = 1024

def scale(p, zero, range, img_size):
    return ((p[0] - zero[0] + range[0] / 2) * img_size[0] / range[0],
            img_size[1] - 
            ((p[1] - zero[1] + range[1] / 2) * img_size[1] / range[1]))


def root(D):
    def f(x):
        return x**(D + 2) - x**(D + 1) - 1

    x0 = float(D - 1) / (D)
    x1 = x0

    while (f(x1) < 0):
        x0 = x1
        x1 *= 2

    # print x0
    # print f(x0)

    # print x1
    # print f(x1)

    while (x1 - x0 > _MIN_ERROR):
        x = (x1 + x0) / 2
        if (f(x) > 0):
            x1 = x
        else:
            x0 = x

    root = (x1 + x0) / 2

    # print root
    # print f(root)
    return root

for d in range(2, 1001):
    r = root(d)
    a = approx(d)
    # D & a & r & log(2, r)
    print '  %d & %f & %f & %f & %f\\\\' % (d, a, r, log(r, 2), a * log(r, 2))

image = Image.new('RGBA', (_IMAGE_SIZE, _IMAGE_SIZE))
image_name = 'fix_point_%f.jpg' % time()
draw = ImageDraw.Draw(image)

d0 = 3.0
step = 10**-1
max_d = 1000

pstep = (max_d - d0) / 100.
pd = d0
d = d0
while (d < max_d):
    if (d >= pd):
        print '%d percent ready' % int(100 * (d - d0) / (max_d - d0))
        pd += pstep

    # mixed algorithm
    p = (d, 2 * log(root(d + 2), 2))
    p = scale(p, [(d0 + max_d) / 2, 0.5], [max_d - d0, 2], [_IMAGE_SIZE, _IMAGE_SIZE])
    draw.point(p, (256, 256, 256))

    # old algorithm
    p = (d, 1 / approx(d))
    p = scale(p, [(d0 + max_d) / 2, 0.5], [max_d - d0, 2], [_IMAGE_SIZE, _IMAGE_SIZE])
    draw.point(p, (0, 102, 255))

    d += step

for x in range(_IMAGE_SIZE):
    draw.point((x, 3 * _IMAGE_SIZE / 4), (256, 0, 0))

del draw
image.save('wykresik.jpg')

